﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
using System.Linq;
using Chaunce.Domain.Table;
using Microsoft.Extensions.Configuration;
using Chaunce.FrameWork.NetCore.IoC;
using Microsoft.AspNetCore.Hosting;
using Chaunce.FrameWork.NetCore.EasyRedis;
using Chaunce.Dao.Contexts;
using Chaunce.Dapper.Repositories;

namespace Chaunce.Service
{
    public class DemoService : IDemoService
    {
        private readonly IUnitOfWork<FirstDbContext> _unitOfWork;
        private readonly IConfiguration _configuration;
        private readonly IHostingEnvironment _environment;
        private readonly IDapperRepository<Company, int> _iDapperRepository;
        private readonly IRedisCache _provider;
        public DemoService(
            IUnitOfWork<FirstDbContext> unitOfWork,
            IConfiguration configuration,
            IDapperRepository<Company, int> iDapperRepository,
            IHostingEnvironment environment,
            IRedisCache provider)
        {
            _unitOfWork = unitOfWork;
            _configuration = configuration;
            _iDapperRepository = iDapperRepository;
            _environment = environment;
            _provider = provider;
        }

        /// <summary>
        /// 数据操作
        /// </summary>
        /// <returns></returns>
        public async Task<Company> Method()
        {
            try
            {
                #region dapper操作
                var valuesdapper = _iDapperRepository.Query(@"select * from Company").FirstOrDefault();
                var entity = _iDapperRepository.Get(1);
                #endregion

                #region EF操作
                var repo = _unitOfWork.GetRepository<Company>();
                var values = await Task.Run(() => { return repo.GetAll(); });
                #endregion
                return values.FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 配置文件操作
        /// </summary>
        /// <returns></returns>
        public string Method1()
        {
            var en = _environment.EnvironmentName;
            var iocEn = IoCContainer.Resolve<IHostingEnvironment>();

            //_iCache.Set("chaunce_test", en);
            //var str1 = _iCache.Get("chaunce_test", s => { return "666"; });
            _provider.CustomPrefixKey = "www:";
            _provider.Set("demo", "yyy", TimeSpan.FromMinutes(1));
            var str2 = _provider.Get("demo", () => { return "缓存"; }, TimeSpan.FromMinutes(1));
            _provider.CustomPrefixKey = "EEE:";
            var str3 = _provider.Get("demo", () => { return "缓存"; }, TimeSpan.FromMinutes(1));

            return str2.ToString();

            //return str1;
            //return ConfigHelper.GetSection("AppSettings").GetSection("JwtBearer")["Key"];
        }
    }
}
